package com.johnny.xia.util.img;

import java.io.File;
import java.io.IOException;

import com.drew.imaging.ImageMetadataReader;
import com.drew.imaging.ImageProcessingException;
import com.drew.metadata.Directory;
import com.drew.metadata.Metadata;
import com.drew.metadata.Tag;
import com.drew.metadata.exif.ExifIFD0Directory;

/**
 * 图片相关数理工具
 * @author johnnyxia
 *
 */
public class PhotoUtil {

	
	public static void getAllMetadataInfo(File file) throws ImageProcessingException, IOException{
		
//		System.out.println(file.getName()+":");
		
		Metadata metadata = ImageMetadataReader.readMetadata(file);
		

		for (Directory directory : metadata.getDirectories()) {
		    for (Tag tag : directory.getTags()) {
		        System.out.format("\n[%s] - %s = %s",
		            directory.getName(), tag.getTagName(), tag.getDescription()+"\n");
		    }
		    if (directory.hasErrors()) {
		        for (String error : directory.getErrors()) {
		            System.err.format("ERROR: %s", error);
		        }
		    }
		}
		
		ExifIFD0Directory exififd0 = metadata.getDirectory(ExifIFD0Directory.class);
		if(exififd0.containsTag(ExifIFD0Directory.TAG_DATETIME)){
			System.out.println("TAG_DATETIME  ==" + exififd0.getDescription(ExifIFD0Directory.TAG_DATETIME));
//			System.out.println("TAG_ORIENTATION == " + exififd0.getDescription(ExifIFD0Directory.TAG_ORIENTATION));
		}
	}
	
	/**
	 * 获取照片的拍摄时间
	 * @param file
	 * @return
	 */
	public static String getDateTime(File file){

		Metadata metadata = null;
		try {
			metadata = ImageMetadataReader.readMetadata(file);
		} catch (Exception e) {
			return null;
		}
		ExifIFD0Directory exififd0 = metadata.getDirectory(ExifIFD0Directory.class);
		if(exififd0 != null && exififd0.containsTag(ExifIFD0Directory.TAG_DATETIME)){
			return exififd0.getDescription(ExifIFD0Directory.TAG_DATETIME);
		}else{
			return null;
		}
	}
}
